/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.ap.web;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.google.gson.Gson;
import com.jeeplus.modules.ap.entity.DamagedDetil;
import com.jeeplus.modules.ap.service.DamagedDetilService;
import com.jeeplus.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.ap.entity.Damaged;
import com.jeeplus.modules.ap.service.DamagedService;

/**
 * 货损货差Controller
 * @author 李超辉
 * @version 2019-07-31
 */
@Controller
@RequestMapping(value = "${adminPath}/ap/damaged")
public class DamagedController extends BaseController {

	@Autowired
	private DamagedService damagedService;
	@Autowired
	private DamagedDetilService damagedDetilService;
	@ModelAttribute
	public Damaged get(@RequestParam(required=false) String id) {
		Damaged entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = damagedService.get(id);
		}
		if (entity == null){
			entity = new Damaged();
		}
		return entity;
	}
	
	/**
	 * 货损货差列表页面
	 */
	@RequiresPermissions("ap:damaged:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/ap/damagedList";
	}
	
		/**
	 * 货损货差列表数据
	 */
	@ResponseBody
	@RequiresPermissions("ap:damaged:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(Damaged damaged, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro= UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			damaged.setPro(pro);
		}
		Page<Damaged> page = damagedService.findPage(new Page<Damaged>(request, response), damaged);
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑货损货差表单页面
	 */
	@RequiresPermissions(value={"ap:damaged:view","ap:damaged:add","ap:damaged:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(Damaged damaged, Model model) {
		if(damaged.getIsNewRecord()){
			String pro= UserUtils.getUseroffice();
			if(!pro.equals("总部")){
				damaged.setPro(pro);
			}
			damaged.setStatus("已创建");
			damaged.setPfstatus("未赔付");
			damaged.setSfwc("未完成");
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			String code=UserUtils.getUserAre()+sdf.format(new Date());
			Damaged p=new Damaged();
			p.setCode(code);
			List<Damaged> l=damagedService.findList(p);
			if(l==null||l.size()<1){
				damaged.setCode(code+"001"+"HS");
			}else{
				if(l.size()/10==0){
					damaged.setCode(code+"00"+(l.size()+1)+"HS");
				}else
				if(l.size()/100==0){
					damaged.setCode(code+"0"+(l.size()+1)+"HS");
				}else{damaged.setCode(code+(l.size()+1)+"HS");}

			}

		}
		model.addAttribute("damaged", damaged);
		return "modules/ap/damagedForm";
	}

	@RequestMapping(value = "ck")
	public String ck(String code, Model model) {
		Damaged damaged=damagedService.findUniqueByProperty("code",code);
		damaged=damagedService.get(damaged.getId());
		model.addAttribute("damaged", damaged);
		return "modules/ap/damagedForm";
	}
	/**
	 * 保存货损货差
	 */
	@ResponseBody
	@RequiresPermissions(value={"ap:damaged:add","ap:damaged:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(Damaged damaged, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, damaged)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		damagedService.save(damaged);//新建或者编辑保存
		j.setSuccess(true);
		j.setMsg("保存货损货差成功");
		return j;
	}
	
	/**
	 * 删除货损货差
	 */
	@ResponseBody
	@RequiresPermissions("ap:damaged:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(Damaged damaged, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		damagedService.delete(damaged);
		j.setMsg("删除货损货差成功");
		return j;
	}

	/**
	 * 确认
	 */
	@ResponseBody
	@RequestMapping(value = "qr")
	public AjaxJson qr(Damaged damaged, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		damaged.setStatus("已确认");
		damagedService.save(damaged);
		j.setMsg("确认成功");
		return j;
	}

	/**
	 * 获取明细
	 */
	@ResponseBody
	@RequestMapping(value = "detil")
	public String detil(Damaged damaged, RedirectAttributes redirectAttributes) {
		DamagedDetil d=new DamagedDetil();
		d.setPid(damaged.getId());
		List<DamagedDetil> list=damagedDetilService.findList(d);
		Gson g=new Gson();
		return g.toJson(list).toString();
	}

	/**
	 * 赔付
	 */
	@ResponseBody
	@RequestMapping(value = "pf")
	public AjaxJson pf(Damaged damaged,String fs,String je,String rq,String sm, RedirectAttributes redirectAttributes) throws ParseException {
		AjaxJson j = new AjaxJson();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		damaged.setPffs(fs);
		damaged.setPfje(je);
		damaged.setPfqkms(sm);
		damaged.setPfrq(sdf.parse(rq));
		damaged.setPfstatus("已赔付");
		damagedService.save(damaged);
		j.setMsg("赔付成功");
		return j;
	}


	/**
	 * 追损
	 */
	@ResponseBody
	@RequestMapping(value = "zs")
	public AjaxJson zs(Damaged d,String fs,String je,String rq,String sm, RedirectAttributes redirectAttributes) throws ParseException {
		AjaxJson j = new AjaxJson();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		DamagedDetil damaged=new DamagedDetil();
		damaged.setFs(fs);
		damaged.setJe(je);
		damaged.setSm(sm);
		damaged.setRq(sdf.parse(rq));
		damaged.setPid(d.getId());
		damagedDetilService.save(damaged);
		String hz=d.getHz();
		String gsbf=d.getGscdje();
		String yzs=d.getZsdzje();
		if(yzs==null||yzs.equals("")){
			yzs="0";
		}
		double zs=Double.parseDouble(yzs)+Double.parseDouble(je);
		d.setZsdzje(zs+"");
		d.setZssj(sdf.parse(rq));
		if((Double.parseDouble(hz)-Double.parseDouble(gsbf))>zs){
			d.setSfwc("部分完成");
		}else{
			d.setSfwc("已完成");
		}
		damagedService.save(d);
		j.setMsg("赔付成功");
		return j;
	}
	/**
	 * 批量删除货损货差
	 */
	@ResponseBody
	@RequiresPermissions("ap:damaged:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			damagedService.delete(damagedService.get(id));
		}
		j.setMsg("删除货损货差成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("ap:damaged:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(Damaged damaged, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "货损货差"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<Damaged> page = damagedService.findPage(new Page<Damaged>(request, response, -1), damaged);
    		new ExportExcel("货损货差", Damaged.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出货损货差记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("ap:damaged:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Damaged> list = ei.getDataList(Damaged.class);
			for (Damaged damaged : list){
				try{
					damagedService.save(damaged);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条货损货差记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条货损货差记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入货损货差失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/ap/damaged/?repage";
    }
	
	/**
	 * 下载导入货损货差数据模板
	 */
	@RequiresPermissions("ap:damaged:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "货损货差数据导入模板.xlsx";
    		List<Damaged> list = Lists.newArrayList(); 
    		new ExportExcel("货损货差数据", Damaged.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/ap/damaged/?repage";
    }

}